using System;
using System.Collections.Generic;
using System.Html;
using System.Runtime.CompilerServices;
using jQueryApi;

namespace LoaTools
{

    public class WidgetTimer
    {
        public int StartTm;
        public int StopTm;
        public int EndTm;
        public int Ticks;
        public int TickUp;
        public int TickDn;
        public int Interval = 1000;
        public int Duration = 1000;
        public Action<WidgetTimer> OnBegin;
        public Action<WidgetTimer> OnEnd;
        public Action<WidgetTimer> OnStart;
        public Action<WidgetTimer> OnStop;
        public Action<WidgetTimer> OnTick;
        public Action<WidgetTimer> OnCancel;
        public List<int> Marks;
        public int Timer;
        public jQueryObject Element;
        public bool Done;
        public jQueryEvent ev;

        public void Trigger()
        {
            TickUp++;
            TickDn--;
            if (OnTick != null)
                OnTick(this);
            if ((new Date()).GetTime() >= EndTm)
            {
                Window.ClearInterval(Timer);
                if (OnEnd != null)
                    OnEnd(this);
                Done = true;
            }
        }

        [AlternateSignature]
        public extern void StartEv();

        public void StartEv(jQueryEvent e)
        {
            ev = e;
            Window.ClearInterval(Timer);
            if (StartTm == 0)
            {
                StartTm = (new Date()).GetTime();
                EndTm = StartTm + Duration;
// ReSharper disable PossibleLossOfFraction
                Ticks = TickDn = Number.ParseInt(Duration/Interval);
// ReSharper restore PossibleLossOfFraction
                if (OnBegin != null)
                    OnBegin(this);
            }
            else
            {
                int dl = (new Date()).GetTime() - StopTm;
                StartTm += dl;
                EndTm += dl;
            }
            if (OnStart != null)
                OnStart(this);
            Timer = Window.SetInterval(Trigger, Interval);
        }

        [AlternateSignature]
        public extern void StopEv();

        public void StopEv(jQueryEvent e)
        {
            ev = e;
            Window.ClearInterval(Timer);
            StopTm = (new Date()).GetTime();
            if (OnStop != null)
                OnStop(this);
        }

        [AlternateSignature]
        public extern void CancelEv();

        public void CancelEv(jQueryEvent e)
        {
            ev = e;
            Done = true;
            Window.ClearInterval(Timer);
            if (OnCancel != null)
                OnCancel(this);
        }

        [AlternateSignature]
        public static extern void PlaySound(jQueryObject sound);

        public static void PlaySound(jQueryObject sound, double volume)
        {
            Script.Literal("{0}.volume = {1}", sound[0], volume);
            Script.Literal("{0}.play()", sound[0]);
        }

    }
}
